
package com.thb.pay.engine;

import com.thb.pay.core.exception.RRException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * InitGroovyScriptTemplate
 *
 * <p>规则项目下模板的初始化</p>
 *
 * @author lucky
 * @since 2019-11-08
 */
@Slf4j
@Service
public class InitGroovyScriptTemplate implements InitializingBean {
    private static final Map<String, String> SCRIPT_TEMPLATE_MAP = new ConcurrentHashMap();
    private static final String DEFAULT_PATH = "classpath*:*.groovy_template";

    public String getScript(String fileName) {
        String template = SCRIPT_TEMPLATE_MAP.get(fileName);
        if (StringUtils.isEmpty(template)) {
            throw RRException.build(String.format("请添加脚本模板: %s 到resources目录下", fileName));
        } else {
            return template;
        }
    }

    private void scriptTemplate() throws IOException {
        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        Arrays.asList(resolver.getResources(DEFAULT_PATH)).forEach((resource) -> {
            try {
                String fileName = resource.getFilename();
                InputStream input = resource.getInputStream();
                InputStreamReader reader = new InputStreamReader(input);
                BufferedReader br = new BufferedReader(reader);
                StringBuilder template = new StringBuilder();

                String line;
                while ((line = br.readLine()) != null) {
                    template.append(line).append("\n");
                }
                SCRIPT_TEMPLATE_MAP.put(fileName, template.toString());
                log.info("load script template :{}", resource.getURL());
            } catch (Exception var7) {
                log.error("read file failed", var7);
            }

        });
    }

    public void afterPropertiesSet() throws Exception {
        this.scriptTemplate();
    }
}
